package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.cluePoolManager.ImportFollowVO;
import com.crm.model.vo.customerManager.CustomerVO;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.model.vo.user.UserAccountManagerVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:chaifuyou
 * @Date: 2021/6/15 13:45
 */
public class InsertFollowCallable  implements Callable<JSONObject> {

    private ClueFollowDbService clueFollowDbService;
    private UserAccountDbService userAccountDbService;
    private ImportFailureLogDbService importFailureLogDbService;
    private CustomerDbService customerDbService;
    private List<ImportFollowVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private String companyId;

    public InsertFollowCallable(ClueFollowDbService clueFollowDbService, List<ImportFollowVO> list, CountDownLatch begin,
                                CountDownLatch end, String companyId, UserAccountDbService userAccountDbService,
                                ImportFailureLogDbService importFailureLogDbService, CustomerDbService customerDbService) {
        this.clueFollowDbService = clueFollowDbService;
        this.userAccountDbService = userAccountDbService;
        this.importFailureLogDbService = importFailureLogDbService;
        this.customerDbService = customerDbService;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.companyId = companyId;
    }

    @SneakyThrows
    @Override
    public JSONObject call() {
        UserAccount loginUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        //导入数量
        int importNum = 0;
        //重复的行数
        //String repeatIdStr = "";
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        //String importFailIdStr = "";
        List<Integer> importFailIdStr = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        for (int i=0;i<list.size();i++) {
            boolean b= true;
            ImportFollowVO importVO = list.get(i);
            List<ImportFailureLogVO> logVOList = importFailureLogDbService.selectImportFailureLogByNameAndType(importVO.getFollowCode(),6,companyId,null);
            if (logVOList.size() > 0){
                for (int k=0;k<logVOList.size();k++){
                    if (logVOList.get(k).getImportData().equals(JSONObject.toJSONString(importVO))){
                        if (logVOList.get(k).getLogType().equals("1")){
                            //重复
                            repeatIdStr.add(i+2);
                        }else if (logVOList.get(k).getLogType().equals("2")){
                            //导入失败
                            importFailIdStr.add(i+2);
                        }
                        b =false;
                        break;
                    }
                }
            }
            if (b){

                UserAccountManagerVO userAccount =userAccountDbService.selectUserAccountByNameAndCompanyId(importVO.getCreateName(),companyId);
                if (Objects.isNull(userAccount)){
                    userAccount = new UserAccountManagerVO();
                }
                CustomerVO customerVO = customerDbService.selectCustomerByName(importVO.getCustomerName());
                if (Objects.isNull(customerVO)){
                    insertImportFailureLog(importVO,2,userAccount,"第"+i+2+"行,客户名称："+importVO.getCustomerName()+"客户匹配失败");
                    //导入失败
                    importFailIdStr.add(i+2);
                }else {
                    //根据创建时间和跟进详情和跟进人id匹配
                    ClueFollowVO clueFollowVO = clueFollowDbService.selectClueFollow(importVO.getCreateTm(),importVO.getFollowDetail(),userAccount.getAccountId(),customerVO.getCustomerId());
                    if (Objects.isNull(clueFollowVO) || Objects.isNull(clueFollowVO.getClueFollowId())){
                        ClueFollow clueFollow =new ClueFollow();
                        clueFollow.setClueFollowId(CommonUtils.getGUID());
                        Date followTm = null;
                        Date createTm = null;
                        if (Objects.nonNull(importVO.getFollowTm())){
                            //同一个Excel有不一样的时间格式……
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            if (importVO.getFollowTm().length() > 16){
                                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            }
                            followTm= simpleDateFormat.parse(importVO.getFollowTm());
                        }
                        if (Objects.nonNull(importVO.getCreateTm())){
                            //同一个Excel有不一样的时间格式……
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            if (importVO.getCreateTm().length() > 16){
                                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            }
                            createTm= simpleDateFormat.parse(importVO.getCreateTm());
                        }
                        clueFollow.setCustomerId(customerVO.getCustomerId());
                        clueFollow.setCreatePeopleId(userAccount.getAccountId());
                        clueFollow.setFollowDetail(importVO.getFollowDetail());
                        clueFollow.setFollowTm(followTm);
                        clueFollow.setCreateTm(createTm);
                        clueFollow.setDataSource(1);
                        Integer followWay = getFollowWay(importVO.getFollowWay());
                        clueFollow.setFollowWay(followWay);
                        clueFollow.setUpdatePeopleId(loginUserAccount.getAccountId());
                        clueFollow.setUpdateTm(new Date());
                        b = clueFollowDbService.insertFollow(clueFollow);
                        if (b){
                            importNum = importNum+1;
                        }else {
                            insertImportFailureLog(importVO,2,userAccount,"数据错误");
                            //导入失败
                            importFailIdStr.add(i+2);
                        }
                    }else {
                        //insertImportFailureLog(importVO,1,userAccount,"第"+i+2+"行,跟进编号："+importVO.getFollowCode()+"数据已存在");
                        //重复
                        repeatIdStr.add(i+2);
                    }
                }

            }
        }
        jsonObject.put("importNum",importNum);
        jsonObject.put("repeatIdStr",repeatIdStr);
        jsonObject.put("importFailIdStr",importFailIdStr);
        return jsonObject;
    }

    private Integer getFollowWay(String followWay) {
        if ("电话".equals(followWay)){
            return 1;
        }
        if ("上门".equals(followWay)){
            return 2;
        }
        if ("微信".equals(followWay) || "QQ".equals(followWay)){
            return 3;
        }
        if ("陪访".equals(followWay)){
            return 6;
        }
        if ("邮件".equals(followWay)){
            return 5;
        }
        if ("业务员手机".equals(followWay)){
            return 4;
        }
        return null;
    }

    /**
     * 记录导入失败日志
     * @param importVO
     * @param type
     */
    public void insertImportFailureLog(ImportFollowVO importVO,Integer type,UserAccountManagerVO userAccount,String reasonForFailure){
        UserAccount logUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        ImportFailureLog importFailureLog = new ImportFailureLog();;
        if (type == 1){
            CustomerVO customerVO = customerDbService.selectCustomerByName(importVO.getCustomerName());
            if (Objects.isNull(customerVO)){
                customerVO = new CustomerVO();
            }
            ClueFollowVO clueFollowVO = clueFollowDbService.selectClueFollow(importVO.getCreateTm(),importVO.getFollowDetail(),userAccount.getAccountId(),customerVO.getCustomerId());
            importFailureLog.setDataId(clueFollowVO.getClueFollowId());
        }
        importFailureLog.setAccountId(userAccount.getAccountId());
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(logUserAccount.getAccountId());
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType("6");
        importFailureLog.setImportName(importVO.getFollowCode());
        importFailureLog.setReasonForFailure(reasonForFailure);
        importFailureLog.setImportData(JSONObject.toJSONString(importVO));
        importFailureLog.setLogType(String.valueOf(type));
        importFailureLog.setCompanyId(companyId);
        importFailureLogDbService.insertImportFailureLog(importFailureLog);
    }
}
